import { promisify } from '../../../utils/promise.util'
import { $init, $digest } from '../../../utils/common.util'
// import config from '../../config'
import util from '../../../utils/util.js';
const wxUploadFile = promisify(wx.uploadFile)
import regeneratorRuntime from '../../../utils/regenerator-runtime/runtime.js'

import { getObjectFromStorgeSync, KEYS } from '../../../utils/http.js';


//获取应用实例
var app = getApp();

Page({

  data: {
    stars: [0, 1, 2, 3, 4],
    normalSrc: '../../../images/starnormal.png',
    selectedSrc: '../../../images/starselected.png',
    halfSrc: '../../../images/starhalf.png',
    key: 0,//评分
    key2: 0,

    titleCount: 0,
    contentCount: 0,
    title: '',
    content: '',
    images: [],
    uploadimg:'',
    orderinfo:'',
  },

  onLoad(options) {
    $init(this);
    let data = JSON.parse(options.data);
    console.log(data);
    this.setData({
      orderinfo: data,
    });

    wx.setNavigationBarTitle({
      title: '发表评论'
    });
  },

  handleTitleInput(e) {
    const value = e.detail.value
    this.data.title = value
    this.data.titleCount = value.length
    $digest(this)
  },

  handleContentInput(e) {
    const value = e.detail.value
    this.data.content = value
    this.data.contentCount = value.length
    $digest(this)
  },

  chooseImage(e) {
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        const images = this.data.images.concat(res.tempFilePaths)
        this.data.images = images.length <= 3 ? images : images.slice(0, 3)
        $digest(this)
      }
    })
  },

  removeImage(e) {
    const idx = e.target.dataset.idx
    this.data.images.splice(idx, 1)
    $digest(this)
  },

  handleImagePreview(e) {
    const idx = e.target.dataset.idx
    const images = this.data.images

    wx.previewImage({
      current: images[idx],
      urls: images,
    })
  },

  submitForm(e) {
    const title = this.data.title
    const content = this.data.content

    var uploadImgCount = 0;
    // var usetinfo = wx.getStorageSync("user_info");
    var usetinfo = util.getData("userinfo");
    this.data.uploadimg = '';
    var that = this;
    if(this.data.key==0|| this.data.key2==0)
    {
      util.showToast('请进行评分');
      return;
    }

    if (content) {
      const arr = []
      var url = app.globalData.SERVER + 'file/picUpload2';
      var i=0;
      var tel = usetinfo.tel;
      if(this.data.images.length == 0)
      {
        this.uploadComment();
      }else{
      for (let path of this.data.images) {

        wx.uploadFile({
          url: url,
          filePath: path,
          tel: tel,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
           
          },
          success: function (res) {
      
            var json = JSON.parse(res.data);

            if (parseInt(json.code)==1)
           {
              var ret = json.ret;
              var pic = ret.url;
            
            var url = that.data.uploadimg;
            if(uploadImgCount != 0)
            {
              url = url +','+pic;
            }else{
              url = pic
            }
            that.setData({
              uploadimg: url
            });
            uploadImgCount++;
            //如果是最后一张,则隐藏等待中  
              if (uploadImgCount == that.data.images.length) {
              wx.hideToast();
              that.uploadComment();

            }
           }else{
             wx.hideToast();
             wx.showModal({
               title: '错误提示',
               content: '上传图片失败',
               showCancel: false,
               success: function (res) { }
             })
           }
          },
          fail: function (res) {
            wx.hideToast();
            wx.showModal({
              title: '错误提示',
              content: '上传图片失败',
              showCancel: false,
              success: function (res) { }
            })
          }
        });  
      }
      }
    } else {
      util.showToast('请输入评论');
      retrun;
    }
     

      

      
    
  },

  async uploadComment(){
    var url = app.globalData.SERVER + 'comment/addRepairComment';

    const shop = await getObjectFromStorgeSync(KEYS.SHOP)
    // var usetinfo = wx.getStorageSync("user_info");
    var usetinfo = util.getData("userinfo");
    var car = util.getData("defaultcar");
    var tel = usetinfo.tel;
    const content = this.data.content;
    var that = this;
    var body = {
      carer: usetinfo._id,
      carerid: usetinfo._id,
      car: car._id,
      carid: car._id,
      repair: that.data.orderinfo._id,
      repairid: that.data.orderinfo._id,
      shop: shop._id,
      shopid: shop._id,
      type: '1',
      serviceattitudestar: that.data.key,
      servicespeedestar: that.data.key2,
      content: content,
      pics: that.data.uploadimg,
      price: that.data.orderinfo.saleMoney,
    };
    util.request(url, 'POST', body).then(res => {
      util.showToast('新增成功', 'error', 1000);
    }).catch(err => {
      if (err.data.code === 1) {
        util.showToast('数据保存成功！', 'success', 1000);
        setTimeout(function () {
          wx.navigateBack({
            delta: -1
          });
        }, 1000)
      } else {
        util.showToast('发表评论失败', 'success', 1000);
      }
    });
  },
  selectLeft: function (e) {
    var key = e.currentTarget.dataset.key
    if (this.data.key == 0.5 && e.currentTarget.dataset.key == 0.5) {
      //只有一颗星的时候,再次点击,变为0颗
      key = 0;
    }
    console.log("得" + key + "分")
    this.setData({
      key: key
    })

  },
  //点击左边,整颗星
  selectRight: function (e) {
    var key = e.currentTarget.dataset.key
    console.log("得" + key + "分")
    this.setData({
      key: key
    })
  },
  selectLeft2: function (e) {
    var key2 = e.currentTarget.dataset.key
    if (this.data.key == 0.5 && e.currentTarget.dataset.key == 0.5) {
      //只有一颗星的时候,再次点击,变为0颗
      key2 = 0;
    }
    // console.log("得" + key2 + "分")
    this.setData({
      key2: key2
    })

  },
  //点击左边,整颗星
  selectRight2: function (e) {
    var key2 = e.currentTarget.dataset.key
    // console.log("得" + key + "分")
    this.setData({
      key2: key2
    })
  },

  selectLeft11: function (e) {
    var key2 = e.currentTarget.dataset.key
    console.log("得" + key + "分")
    this.setData({
      key2: key2
    })
  },

})